<template>
    <div class="smart-filter">
        <template v-if="type === 'date' || type === 'datetime'">
            <div class="filter-tips">选择日期范围进行筛选</div>
            <el-date-picker v-model="innerValue" type="daterange" :unlink-panels="false" range-separator="至"
                start-placeholder="开始日期" end-placeholder="结束日期" size="small" clearable class="date-picker-full"
                @change="onDateChange" />
        </template>
        <template v-else>
            <el-select v-model="innerValue" clearable filterable placeholder="选择筛选项" size="small" class="select-full">
                <el-option v-for="opt in options" :key="String(opt.value)" :label="String(opt.text ?? opt.value)"
                    :value="opt.value" />
            </el-select>
        </template>

        <div class="filter-actions">
            <el-button size="small" type="primary" @click="apply">应用</el-button>
            <el-button size="small" @click="clear">清空</el-button>
        </div>
    </div>
</template>

<script setup>
import { ref, watch } from 'vue'

const props = defineProps({
    type: { type: String, default: 'string' },
    options: { type: Array, default: () => [] },
    modelValue: { type: [String, Number, Array, Object, null], default: null },
})

const emit = defineEmits(['update:modelValue', 'apply', 'clear'])

const innerValue = ref(props.modelValue)

watch(() => props.modelValue, v => innerValue.value = v)

const apply = () => {
    emit('update:modelValue', innerValue.value)
    emit('apply', innerValue.value)
}

const clear = () => {
    innerValue.value = null
    emit('update:modelValue', null)
    emit('clear')
}

const onDateChange = (val) => {
    // 实时保存并打印，避免用户以为选择丢失
    innerValue.value = val
    console.log('[SmartFilter][date-range-change]:', val)
}
</script>

<style scoped>
.smart-filter {
    min-width: 260px;
}

.filter-tips {
    margin-bottom: 8px;
    font-size: 12px;
    color: var(--el-text-color-secondary);
}

.date-picker-full,
.select-full {
    width: 100%;
}

.filter-actions {
    margin-top: 10px;
    display: flex;
    justify-content: flex-end;
    gap: 8px;
}

/* 让弹层内容在容器中更居中 */
.smart-filter :deep(.el-date-editor) {
    width: 100%;
}
</style>
